package com.inspur.common.utils;

import java.lang.reflect.Field;
import java.util.Date;

import org.json.JSONObject;

import com.inspur.common.UserInfo;

public class JsonUtil {

    public static Object fromJsonToModel(JSONObject json,Class pojo) throws Exception{
        // ���ȵõ�pojo������ֶ�
        Field [] fields = pojo.getDeclaredFields();
        // ��ݴ����Class��̬���pojo����
        Object obj = pojo.newInstance();
        for(Field field: fields){
            // �����ֶοɷ��ʣ����룬���򱨴?
            field.setAccessible(true);
            // �õ��ֶε�������
            String name = field.getName();
            // ��һ�ε�����������ֶ���JSONObject�в����ڻ��׳��쳣�������쳣�������
            try{
                    json.get(name);
            }catch(Exception ex){
                continue;
            }
            if(json.get(name) != null && !"".equals(json.getString(name))){
                // ����ֶε����ͽ�ֵת��Ϊ��Ӧ�����ͣ������õ���ɵĶ����С�
                if(field.getType().equals(Long.class) || field.getType().equals(long.class)){
                    field.set(obj, Long.parseLong(json.getString(name)));
                }else if(field.getType().equals(String.class)){
                    field.set(obj, json.getString(name));
                } else if(field.getType().equals(Double.class) || field.getType().equals(double.class)){
                    field.set(obj, Double.parseDouble(json.getString(name)));
                } else if(field.getType().equals(Integer.class) || field.getType().equals(int.class)){
                    field.set(obj, Integer.parseInt(json.getString(name)));
                } else if(field.getType().equals(java.util.Date.class)){
                    field.set(obj, Date.parse(json.getString(name)));
                }else{
                    continue;
                }
            }
        }
        return obj;
    }
    
    public static void main() throws Exception{
    	String str = "{'access_time_a':'','access_time_z':'','accessdate':'1,1,1,1,1,1,1','authoritytree':{},'compname':'ʡ����','createman':2,'createmanaccount':'admin','createtime':'2013-04-08 15:02:55','destroytime':'','empid':101521,'empname':'���','groupid':0,'grpmember':[],'listfuncs':[],'listres':[],'locked':0,'managerlistname':'','password':'3696441120a402f793a704766540e69e','remark':'','unitname':'ʡ����-�������','updatetime':'2013-04-08 15:02:55','useraccount':'inspur','userfunc':[],'userid':52515,'userrole':[]}";
    	JSONObject jsonObj = new JSONObject(str);
    	UserInfo userInfo = (UserInfo)JsonUtil.fromJsonToModel(jsonObj, UserInfo.class);
    	System.out.println(userInfo.getUseraccount());
    	
    }
}
